<!--端口检测-->
<template>
  <div class="h-[100%] box-border w-[100%]">
    <el-card shadow="always">
      <el-form size="default" inline="true" label-width="auto" class="translate-y-2">
        <el-form-item  label="SN:">
          <el-input
            style="width: 240px; height: 100%;"
            placeholder="例:kk"
            v-model="dataParams.sn"
            clearable
          />
        </el-form-item>
        <el-form-item label="设备OTA端口：">
          <el-input
            style="width: 240px"
            placeholder="例:kk"
            v-model="dataParams.srcPort"
            clearable
          />
        </el-form-item>
        <el-form-item label="分组">
          <el-select
            style="width: 200px"
            v-model="dataParams.groupId"
            placeholder="请选择分组"
            clearable
            filterable
            @change="
              (v) => {
                dataParams.groupId = v;
                getForwardDataList();
              }
            "
          >
            <el-option
              v-for="item in dataListGroupSelect"
              :label="item.groupName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            style="width: 240px"
            placeholder="例:kk"
            v-model="dataParams.remark"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button :icon="Refresh" type="primary" @click="getForwardDataList"
            >搜索
          </el-button>
          <el-button
            :icon="Sunny"
            type="primary"
            @click="openForwardDialog(true, null)"
            >添加
          </el-button>

          <el-button
            v-if="false"
            :icon="Download"
            type="primary"
            @click="downloadAddTempServerToServer"
            >批量添加模板下载
          </el-button>
          <el-button
            v-if="false"
            :icon="Upload"
            type="info"
            @click="
              () => {
                batchAddDialog = true;
                batchAdd = {
                  file: null,
                  remark: '',
                };
                if (uploadForm) {
                  uploadForm.clearFiles();
                }
              }
            "
            >批量添加
          </el-button>
          <el-button type="primary" :icon="Sunny" @click="openRtcmGroupDialog"
            >分组管理
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="flex h-[90%] mt-2">
      <el-card style="width: 100%; height: 100%">
        <el-table
          height="65vh"
          :border="true"
          :data="dataList"
          v-loading="tableLoading"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="sn" label="SN" width="150"></el-table-column>
          <el-table-column prop="srcPort" label="OTA端口" />
          <el-table-column prop="srcConnectSize" label="OTA连接数量">
            <template #default="scope">
              <el-tag
                effect="light"
                style="width: 3vw"
                :type="scope.row.srcConnectSize == 0 ? 'danger' : 'success'"
              >
                {{ scope.row.srcConnectSize }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="forwardDataSize" label="转发数据量(KB)" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column
            prop="createdAt"
            label="最新数据转发时间"
            :formatter="
              (row) => dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss')
            "
          />
          <el-table-column prop="groupName" label="分组" />
          <el-table-column prop="status" label="启用状态">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#B9B9B9"
                :active-value="true"
                :inactive-value="false"
                @change="startCloseDataForward(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button
                :icon="Edit"
                @click="openForwardDialog(false, scope.row)"
                >编辑
              </el-button>
              <el-button
                :icon="Delete"
                type="danger"
                @click="deleteDataForward(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="w-[100%] mt-4 flex justify-end">
          <el-pagination
            v-model:current-page="dataParams.pageNum"
            v-model:page-size="dataParams.pageSize"
            :page-sizes="[10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="dataTotal"
            @size-change="
              (number) => {
                getForwardDataList();
              }
            "
            @current-change="
              (number) => {
                getForwardDataList();
              }
            "
          />
        </div>
      </el-card>
    </div>
  </div>
  <el-dialog
    draggable
    v-model="dialogStatusInfo.forwardDialog"
    :title="dialogStatusInfo.title"
    width="500"
  >
    <el-form inline label-width="100" ref="addForm">
      <el-form-item label="Sn:" prop="sn">
        <el-input v-model="addDataForward.sn" placeholder="请输入Sn"></el-input>
      </el-form-item>
      <el-form-item label="OTA端口:" prop="srcPort">
        <el-input
          v-model.number="addDataForward.srcPort"
          placeholder="请输入OTA端口"
        ></el-input>
      </el-form-item>
      <el-form-item label="分组:" prop="groupId">
        <el-select
          style="width: 200px"
          v-model="addDataForward.groupId"
          placeholder="请选择分组"
          clearable
          filterable
        >
          <el-option
            v-for="item in dataListGroupSelect"
            :label="item.groupName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注:" prop="remark">
        <el-input
          v-model="addDataForward.remark"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          :icon="CloseBold"
          @click="dialogStatusInfo.forwardDialog = false"
          >关闭
        </el-button>
        <el-button :icon="Check" type="primary" @click="addForwardData">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--    批量添加dialog-->
  <el-dialog draggable v-model="batchAddDialog" width="1000">
    <el-form inline>
      <el-form-item label="备注：">
        <el-input
          v-model="batchAdd.remark"
          placeholder="请输入备注信息"
        ></el-input>
      </el-form-item>
      <el-form-item label="模板：" label-width="150px">
        <el-upload
          :limit="1"
          ref="uploadForm"
          :auto-upload="false"
          action="#"
          @change="
            (e) => {
              batchAdd.file = e.raw;
            }
          "
        >
          <template #trigger>
            <el-button style="width: 10vw" type="primary"
              >点击模板上传
            </el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchAddDialog = false">取消</el-button>
        <el-button type="primary" @click="batchAddDataForwardFunction">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!--    分组弹窗-->
  <el-dialog v-model="rtcmGroupDialog" title="分组管理">
    <div>
      <el-form inline label-width="100">
        <el-form-item label="操作选择:">
          <el-select style="width: 120px" v-model="isSelectGroup">
            <el-option label="查询" :value="true"></el-option>
            <el-option label="添加" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isSelectGroup" label="分组查询:" prop="groupName">
          <el-input
            placeholder="请输入分组名称"
            v-model="rtcmGroupSelectParams.name"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item v-if="isSelectGroup">
          <el-button @click="getRtcmGroupList" type="primary">搜索 </el-button>
        </el-form-item>
        <el-form-item v-if="!isSelectGroup" label="分组添加:" prop="groupName">
          <el-input
            placeholder="请输入需要添加分组名称"
            v-model="rtcmGroupAddOrEdit.groupName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isSelectGroup">
          <el-button @click="addRtcmGroup" type="primary">添加 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      height="50vh"
      :border="true"
      :data="rtcmGroupList"
      v-loading="tableLoading"
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column prop="id" label="ID" width="150"></el-table-column>
      <el-table-column prop="groupName" label="组名">
        <template #default="scope">
          <span v-if="scope.row.flag">{{ scope.row.groupName }}</span>
          <el-input
            @blur="editRtcmGroup(scope.row)"
            v-else
            v-model="scope.row.groupName"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template #default="scope">
          <el-button
            @click="
              () => {
                scope.row.flag = !scope.row.flag;
              }
            "
            :icon="Edit"
            >编辑
          </el-button>
          <el-button
            :icon="Delete"
            type="danger"
            @click="deleteRtcmGroup(scope.row.id)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="rtcmGroupSelectParams.pageNum"
        v-model:page-size="rtcmGroupSelectParams.pageSize"
        :page-sizes="[10, 20]"
        :size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="rtcmGroupListTotal"
        @size-change="
          (number) => {
            getRtcmGroupList();
          }
        "
        @current-change="
          (number) => {
            getRtcmGroupList();
          }
        "
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import { ElMessage, ElLoading } from "element-plus";
import {
  Delete,
  Refresh,
  Sunny,
  CloseBold,
  Check,
  Upload,
  Download,
  Edit,
} from "@element-plus/icons-vue";
import type { ComponentSize } from "element-plus";
import {
  AddForwardApi,
  UpdateForwardApi,
  DeleteForwardApi,
  SelectPortListApi,
  StartCloseForwardApi,
  DownloadAddTempServerToServerApi,
  BatchAddDataForwardServerToServerApi,
} from "../../service/port";
import type { SearchPortParams } from "../../service/port";
import type { ForwardAddParams } from "../../service/port";
import type { StartCloseParams } from "../../service/port";
import dayjs from "dayjs";
import type { AnyMxRecord } from "dns";
import type { RtcmGroupDTO, RtcmGroupSelectParams } from "@/api/rtcmGroup";
import {
  addRtcmGroupAPI,
  deleteRtcmGroupAPI,
  getRtcmGroupListAPI,
  updateRtcmGroupAPI,
} from "@/api/rtcmGroup";

/**
 * 公共数据
 */
const tableLoading = ref(false);
const addForm = ref();
//弹窗修改状态信息
const dialogStatusInfo = ref({
  isAdd: true,
  forwardDialog: false,
  title: "",
});

/**
 * 弹窗打开函数
 */
const openForwardDialog = (flag: boolean, row: any) => {
  if (flag) {
    dialogStatusInfo.value.forwardDialog = true;
    dialogStatusInfo.value.isAdd = true;
    dialogStatusInfo.value.title = "转发记录添加";
    return;
  }
  if (row.status) {
    ElMessage.warning("启用状态禁止编辑");
    return;
  }
  dialogStatusInfo.value.forwardDialog = true;
  dialogStatusInfo.value.isAdd = false;
  dialogStatusInfo.value.title = "转发记录编辑";
  addDataForward.value.remark = row.remark;
  addDataForward.value.sn = row.sn;
  addDataForward.value.srcPort = row.srcPort;
  addDataForward.value.tarPort = row.tarPort;
  addDataForward.value.id = row.id;
  addDataForward.value.outProtocol = row.outProtocol;
  addDataForward.value.groupId = row.groupId;
};

/**
 * 转发数据获取*************************
 */
//数据列表
const dataList = ref([]);
const dataTotal = ref(0);
//数据查询参数
const dataParams = ref<SearchPortParams>({
  pageSize: 10,
  pageNum: 1,
  sn: "",
  remark: "",
  srcPort: undefined,
  groupId: undefined,
});
const getForwardDataList = async () => {
  tableLoading.value = true;
  const res = await SelectPortListApi(dataParams.value);
  if (res.data.list == null) {
    dataList.value = [];
  } else {
    dataList.value = res.data.list.map((v) => {
      v.forwardDataSize = v.forwardDataSize.toFixed(1);
      return v;
    });
  }
  dataTotal.value = res.data.total;
  tableLoading.value = false;
};
/**
 * 转发数据记录添加
 */
//记录添加表单数据
const addDataForward = ref<ForwardAddParams>({
  id: undefined,
  srcPort: undefined,
  tarPort: 0,
  groupId: undefined,
  remark: "",
  sn: "",
  status: false,
  outProtocol: 1,
});
const addForwardData = async () => {
  console.log("编辑或添加信息", addDataForward.value);
  if (dialogStatusInfo.value.isAdd) {
    const res = await AddForwardApi(addDataForward.value);
    if (res.code == 200) {
      ElMessage.success("新增成功");
      dialogStatusInfo.value.forwardDialog = false;
      getForwardDataList();
    } else {
      ElMessage.error(res.data);
    }
  } else {
    console.log("调用编辑按钮");
    const res = await UpdateForwardApi(addDataForward.value);
    if (res.code == 200) {
      ElMessage.success("编辑成功");
      dialogStatusInfo.value.forwardDialog = false;
      getForwardDataList();
    } else {
      ElMessage.error(res.data);
    }
  }
};

/**
 * 转发记录删除
 */
const deleteDataForward = async (row: any) => {
  if (row.status) {
    ElMessage.warning("启用状态禁止删除");
    return;
  }
  const res = await DeleteForwardApi(row.id);
  if (res.code == 200) {
    ElMessage.success("删除成功");
  } else {
    ElMessage.error(res.data);
  }
  getForwardDataList();
};

/**
 * 开启或者关闭转发服务
 */

const startCloseDataForward = async (row) => {
  const params: StartCloseParams = {};
  params.srcPort = row.srcPort;
  params.tarPort = row.tarPort;
  params.flag = row.status;
  const res = await StartCloseForwardApi(params);
  if (res.code == 200) {
    ElMessage.success("执行成功");
  } else {
    ElMessage.error(res.data);
  }
  getForwardDataList();
};

/**
 * 批量添加模板下载
 */
const batchAddDialog = ref(false);
const downloadAddTempServerToServer = async () => {
  const res = await DownloadAddTempServerToServerApi();
  const link = document.createElement("a");
  try {
    let blob = new Blob([res], { type: "application/vnd.ms-excel" });

    link.style.display = "none";
    // 兼容不同浏览器的URL对象
    const url = window.URL || window.webkitURL || window.moxURL;

    link.href = url.createObjectURL(blob);
    link.setAttribute("download", "example.xlsx");

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    url.revokeObjectURL(link.href); //销毁url对象
    ElMessage.warning("文件下载中");
  } catch (e) {
    console.log("下载的文件出错", e);
  }
};

/**
 * 批量添加
 */
const batchAdd = ref<{ remark: string; file: any }>({
  remark: "",
  file: null,
});
const uploadForm = ref();

const batchAddDataForwardFunction = async () => {
  if (batchAdd.value.file == null || batchAdd.value.remark == "") {
    ElMessage.warning("请完善提交参数");
    return;
  }
  const data = new FormData();
  data.append("file", batchAdd.value.file);
  data.append("remark", batchAdd.value.remark);
  const res = await BatchAddDataForwardServerToServerApi(data);
  if (res.code == 200) {
    ElMessage.success("批量添加成功");
  } else {
    ElMessage.error(res.data);
  }
  batchAddDialog.value = false;
  getForwardDataList();
};

/**
 * 分组相关
 */
const isSelectGroup = ref(true);
const rtcmGroupDialog = ref(false);
const rtcmGroupList = ref([]);
const rtcmGroupSelectParams = ref<RtcmGroupSelectParams>({
  pageSize: 10,
  pageNum: 1,
  name: "",
});
const rtcmGroupListTotal = ref(0);
const rtcmGroupAddOrEdit = ref<RtcmGroupDTO>({
  groupName: "",
});
const getRtcmGroupList = async () => {
  const res = await getRtcmGroupListAPI(rtcmGroupSelectParams.value);
  if (res.code == 200) {
    rtcmGroupList.value = res.data.list === null ? [] : res.data.list;
    rtcmGroupList.value.map((item) => {
      item["flag"] = true;
    });
    rtcmGroupListTotal.value = res.data.total;
  } else {
    ElMessage.error("查询分组异常");
  }
};

//添加ntrip分组
const addRtcmGroup = async () => {
  if (!rtcmGroupAddOrEdit.value.groupName) {
    ElMessage.warning("分组名称不能为空");
    return;
  }
  const res = await addRtcmGroupAPI(rtcmGroupAddOrEdit.value);
  if (res.code == 200) {
    ElMessage.success("添加成功");
    getRtcmGroupList();
    dataListGroupSelectFn();
  } else {
    ElMessage.error("添加失败");
  }
};
/**
 * 删除分组
 */
const deleteRtcmGroup = async (id: number) => {
  const res = await deleteRtcmGroupAPI(id);
  if (res.code == 200) {
    ElMessage.success("删除成功");
    getRtcmGroupList();
  } else {
    ElMessage.error(res.data);
  }
};

/**
 * 编辑分组
 */
const editRtcmGroup = async (row: any) => {
  row.flag = !row.flag;
  console.log("编辑分组", row);
  const res = await updateRtcmGroupAPI({
    id: row.id,
    groupName: row.groupName,
  });
  if (res.code == 200) {
    ElMessage.success("修改成功");
    getRtcmGroupList();
  } else {
    ElMessage.error(res.data);
  }
};
const openRtcmGroupDialog = async () => {
  await getRtcmGroupList();
  rtcmGroupDialog.value = true;
};

/**
 * 分组筛选或者查询
 */
const dataListGroupSelect = ref([]);
const dataListGroupSelectFn = async () => {
  const res = await getRtcmGroupListAPI({
    pageSize: 10000,
    pageNum: 1,
  });
  if (res.code == 200) {
    dataListGroupSelect.value = res.data.list === null ? [] : res.data.list;
  } else {
    ElMessage.error("查询分组异常");
  }
};

/**
 *  周期钩子函数********************************
 */

onMounted(() => {
  getForwardDataList();
  dataListGroupSelectFn();
  console.log("端口转发页面加载", this);
});
</script>

<style scoped>
.container {
  box-sizing: border-box;
  height: 100%;
}

::v-deep(.el-table .success) {
  background-color: #e9ffdb;
}

::v-deep(.el-table .fail) {
  background-color: #ffc87c;
}

[type="file"] {
  color: red;
  /* font-size: 0; */
}

/* 主按钮的样式自定义 */
::file-selector-button {
  height: 2.5rem;
  color: #fff;
  border-radius: 0.25rem;
  border: 1px solid #2a80eb;
  padding: 0.75rem 1rem;
  background-color: #2a80eb;
  cursor: pointer;
}

::-ms-browse {
  height: 3rem;
  color: #fff;
  border-radius: 0.25rem;
  border: 1px solid #2a80eb;
  padding: 0.75rem 1rem;
  background-color: #2a80eb;
  cursor: pointer;
}

.page {
  position: absolute;
  bottom: 10px;
  left: 400px;
}

/*
.cardData {
  position: relative;
  height: 95%;
} */

.card {
  /* width: 80vw; */
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.card2 {
  height: 80px;
  width: 200px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.isActive {
  background-color: red;
  color: bisque;
}

.header {
  /* background-color: rgb(240, 240, 240); */
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 10%;
}

.main {
  display: flex;
  height: 90%;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
